<!-- 入库单设置 -->
<script setup lang="ts">
import type { VbenFormProps } from '#/adapter/form';
import type {
  OnActionClickParams,
  VxeGridListeners,
  VxeGridProps,
} from '#/adapter/vxe-table';
import type { ItemRecpt } from '#/api';

import { ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';
import { VxeButton } from '@vben/plugins/vxe-table';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { deleteItemRecpt, getItemRecptTableList } from '#/api';
import { mergeToolbarButtons, updateToolbarButtonStatus } from '#/utils';

import { confirm, messageError, messageSuccess } from '../common/common';
import { useColumns } from './data';
import ItemRecptForm from './form.vue';

const btn = mergeToolbarButtons().value;
const [FormModal, formModalApi] = useVbenModal({
  connectedComponent: ItemRecptForm,
  destroyOnClose: true,
});

// 存储选中行的响应式变量
const selectedRows = ref<any[]>([]);

/**
 * 编辑
 * @param row
 */
function onEdit(row: ItemRecpt.Row) {
  row.attr1 = '2';
  formModalApi.setData(row).open();
}

/**
 * 查看
 * @param row
 */
function onView(row: ItemRecpt.Row) {
  row.attr1 = '1';
  formModalApi.setData(row).open();
}

/**
 * 创建
 */
function onAdd() {
  formModalApi.setData(null).open();
}

/**
 * 删除
 * @param row
 */
function onDelete(row: ItemRecpt.Row | ItemRecpt.Row[]) {
  const ids = Array.isArray(row)
    ? row.map((item) => item.recptId)
    : [row.recptId];
  const idString = ids.join(',');
  confirm(`确定要删除物料入库单吗？`, '提示').then(() => {
    deleteItemRecpt(idString)
      .then(() => {
        messageSuccess(`删除成功`);
        refreshGrid();
      })
      .catch((error) => {
        messageError(error);
      });
  });
}

const formOptions: VbenFormProps = {
  // 默认展开
  collapsed: false,
  wrapperClass: 'grid-cols-3',
  schema: [
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入入库单编号',
        class: 'mr-5',
      },
      fieldName: 'recptCode',
      label: '入库单编码',
      labelClass: ' text-[#606266] font-bold',
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入入库单名称',
      },
      fieldName: 'recptName',
      label: '入库单名称',
      labelClass: 'text-[#606266] font-bold',
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入供应商名称',
      },
      fieldName: 'vendorName',
      label: '供应商名称',
      labelClass: '  text-[#606266] font-bold',
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入采购订单编号',
      },
      fieldName: 'poCode',
      label: '采购订单编号',
      labelClass: '  text-[#606266] font-bold',
    },
    {
      component: 'DatePicker',
      componentProps: {
        placeholder: '请选择入库日期',
      },
      fieldName: 'recptDate',
      label: '入库日期',
      labelClass: '  text-[#606266] font-bold',
    },
  ],

  // 控制表单是否显示折叠按钮
  showCollapseButton: false,
  submitButtonOptions: {
    content: '搜索',
  },
  // 是否在字段值改变时提交表单
  submitOnChange: false,
  // 按下回车时是否提交表单
  submitOnEnter: false,
};

const gridOptions: VxeGridProps<ItemRecpt.Row> = {
  columns: useColumns(onView, onActionClick),
  checkboxConfig: {
    highlight: true,
  },
  // 虚拟滚动配置项
  virtualYConfig: { enabled: true },
  keepSource: true,
  pagerConfig: {
    enabled: true,
    layouts: [
      'Total',
      'Sizes',
      'PrevJump',
      'PrevPage',
      'Number',
      'NextPage',
      'NextJump',
      'FullJump',
    ],
    align: 'right',
  },
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues) => {
        const res = await getItemRecptTableList({
          pageNum: page.currentPage,
          pageSize: page.pageSize,
          ...formValues,
        });
        return { items: res.rows, total: res.total };
      },
    },
  },
  tooltipConfig: {
    // 是否开启全局文本提示
    showAll: false,
  },
  toolbarConfig: {
    // 是否显示搜索表单控制按钮
    // @ts-ignore 正式环境时有完整的类型声明
    search: true,
    custom: true,
    zoom: true,
    refresh: { code: 'query' },
    buttons: btn,
    // buttons: mergeToolbarButtons([{ name: '测试', code: 'add', status: 'primary', icon: 'vxe-icon-add' }]).value
  },
};

const gridEvents: VxeGridListeners = {
  toolbarButtonClick({ code }) {
    switch (code) {
      case 'add': {
        onAdd();
        break;
      }
      case 'edit': {
        if (selectedRows.value.length === 1) {
          onEdit(selectedRows.value[0] as any);
        } else {
          confirm('请选择单行', '提示');
        }
        break;
      }
      case 'myDelete': {
        if (selectedRows.value.length > 0) {
          onDelete(selectedRows.value);
        }
        break;
      }
      default: {
        break;
      }
    }
    updateToolbarButtonStatus(selectedRows, btn); // 更新按钮状态
  },
  checkboxChange() {
    selectedRows.value = gridApi?.grid?.getCheckboxRecords();
    updateToolbarButtonStatus(selectedRows, btn); // 更新按钮状态
  },
  checkboxAll() {
    selectedRows.value = gridApi?.grid?.getCheckboxRecords();
    updateToolbarButtonStatus(selectedRows, btn); // 更新按钮状态
  },
};

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
  gridEvents,
});

/**
 * 处理表格操作列点击事件的函数
 *
 * @param {OnActionClickParams<ItemRecpt.Row>} - 包含操作代码和行数据的对象
 */
function onActionClick({ code, row }: OnActionClickParams<ItemRecpt.Row>) {
  switch (code) {
    case 'edit': {
      onEdit(row);
      break;
    }
    case 'myDelete': {
      onDelete(row);
      break;
    }
    case 'onStock': {
      // onView(row);
      break;
    }
    case 'onView': {
      onView(row);
      break;
    }
    default: {
      break;
    }
  }
  updateToolbarButtonStatus(selectedRows); // 更新按钮状态
}

/**
 * 刷新表格
 */
function refreshGrid() {
  gridApi.query();
}
</script>

<template>
  <div class="vp-raw w-full">
    <FormModal @success="refreshGrid" />
    <Grid>
      <template #action="{ row }">
        <div v-if="row.status === 'PREPARE'">
          <VxeButton
            mode="text"
            icon="vxe-icon-signature"
            @click="onActionClick({ code: 'edit', row })"
            status="primary"
          >
            编辑
          </VxeButton>
          <VxeButton
            icon="vxe-icon-delete"
            mode="text"
            @click="onActionClick({ code: 'myDelete', row })"
            status="error"
          >
            删除
          </VxeButton>
        </div>
        <div v-else-if="row.status === 'APPROVING'">
          <VxeButton
            mode="text"
            icon="vxe-icon-click-button"
            @click="onActionClick({ code: 'onStock', row })"
            status="primary"
          >
            执行上架
          </VxeButton>
        </div>
      </template>
    </Grid>
  </div>
</template>

<style scoped>
.blue-text {
  color: #1890ff;
}
</style>
